
package com.heimali.happyreader.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

import com.heimali.happyreader.HappyReaderApplication;

public class NetCheckUtils {

    public static final String CONNECTIVITY_CHANGE_ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
    private static ConnectivityManager cm = null;

    public static ConnectivityManager getConnectivityManager() {
        if (cm == null) {
            cm = (ConnectivityManager) HappyReaderApplication.getApplication().getSystemService(
                    HappyReaderApplication.CONNECTIVITY_SERVICE);
        }
        return cm;
    }

    public static boolean isNetworkAvailable() {
        ConnectivityManager cm = getConnectivityManager();
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.isAvailable() && info.isConnected());
    }

    public static boolean isTypeNetwork(int TYPE) {
        ConnectivityManager cm = getConnectivityManager();
        NetworkInfo info = cm.getActiveNetworkInfo();
        return (info != null && info.getType() == TYPE && info.isAvailable() && info.isConnected());
    }

    public static String getNetTypeName() {
        String name = "unknown";
        try {
            if (NetCheckUtils.isTypeNetwork(ConnectivityManager.TYPE_WIFI)) {
                name = "wifi";
            } else if (NetCheckUtils.isTypeNetwork(ConnectivityManager.TYPE_MOBILE)) {
                name = "3g";
            }
        } catch (Exception e) {
            e.printStackTrace();
            name = "unknown";
        }
        return name;
    }

    /**
     * 获取当前移动网络制式，如3G或2G(返回值参考：android.telephony.TelephonyManager.
     * NETWORK_TYPE_XXX)
     * 
     * @return
     */
    public static int getNetworkType() {
        TelephonyManager tm = (TelephonyManager) HappyReaderApplication.getApplication().getSystemService(
                Context.TELEPHONY_SERVICE);
        return tm.getNetworkType();
    }

    /**
     * 监听网络变化
     * @param receiver
     */
    public static void registerDataTransReceiver(BroadcastReceiver receiver) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(CONNECTIVITY_CHANGE_ACTION);
        filter.setPriority(1000);
        HappyReaderApplication.getContext().registerReceiver(receiver, filter);
    }
    

}
